// let mysql = require('mysql')
let moment = require('moment');

// let connection = mysql.createConnection({
//     host: 'localhost',
//     user: 'root',
//     password: 'root',
//     database: 'blog'
// })

// connection.connect()
let connection = require('./db')

module.exports = {
    postNewArticle: (article, callback) => {
        let sqlStr = 'insert into articles set ?'
        connection.query(sqlStr, article, (err, results) => {
            if (err) return callback(err, null)
            callback(null, results)
        })
    },
    getArticleById: (id, callback) => {
        var sqlStr = 'select articles.*, users.nickname from articles LEFT JOIN users on articles.authorId=users.id where articles.id=?'
        // !!!!!!!!!!!!!!!!!! 这里的循环我不懂
        connection.query(sqlStr, id, (err, results) => {
            if (err) return callback(err, null)
            results.forEach(article => {
                article.ctime = moment(article.ctime).format('YYYY-MM-DD HH:mm:ss');
            });
            // results.ctime='2018-12-9 12:02:02';
            callback(null, results)
        })

    },
    editArticle:(article,callback)=>{
        let sqlStr='update articles set ? where id=?'
        connection.query(sqlStr,[article,article.id],(err,results)=>{
            if(err) return callback(err)
            results.id=article.id
            callback(null,results);
        })
    },
    showArticleEdit:(id,callback)=>{
        let sqlStr='SELECT * FROM `articles` WHERE `id` = ?'
        connection.query(sqlStr,[id],(err,results)=>{
            if(err) return callback(err,null)
            console.log(results)
            // return
            // results.id=id
            callback(null,results)
        })
    },
    getArticlesByPage(callback) {
        var sqlStr = 'select articles.*, users.nickname from articles left join users on articles.authorId=users.id';
        connection.query(sqlStr, (err, results) => {
          if (err) return callback(err)
          callback(null, results)
        })
      }
}